//
//  CustomTextView.m
//  CC
//
//  Created by Calvin on 5/21/15.
//  Copyright (c) 2015 Calvin. All rights reserved.
//

#import "CustomTextView.h"

@interface CustomTextView()
@property (nonatomic,weak) UILabel *placeholderLabel;
@end

@implementation CustomTextView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        UILabel *placeholderLabel = [[UILabel alloc] init];
        placeholderLabel.numberOfLines=0;
        placeholderLabel.backgroundColor=[UIColor clearColor];
        [self addSubview:placeholderLabel];
        self.placeholderLabel = placeholderLabel;
        self.placeholderColor = [UIColor lightGrayColor];
        self.font=[UIFont systemFontOfSize:14];
        //register notification listener text change
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 
-(void)textDidChange
{
    if (self.text.length==0) {
        self.placeholderLabel.hidden=NO;
    }
    else
    {
        self.placeholderLabel.hidden=YES;
    }
    self.placeholderLabel.hidden=(self.text.length!=0);
    
    if ([self.textChangeddelegate respondsToSelector:@selector(changeComposePhotoViewHeight:)]) {
        self.textChangeddelegate = (id)self;
    }
}


#pragma mark 占位文字
-(void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    self.placeholderLabel.text = placeholder;
    [self setNeedsLayout];
}

-(void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    self.placeholderLabel.textColor = placeholderColor;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat x = 5;
    CGFloat y = 8;
    CGFloat w = self.frame.size.width - 2 * self.placeholderLabel.frame.origin.x;
    CGSize maxSize = CGSizeMake(self.frame.size.width, MAXFLOAT);
    CGSize placeholderSize = [self.placeholder sizeWithFont:self.placeholderLabel.font constrainedToSize:maxSize];
    CGFloat h = placeholderSize.height;
    self.placeholderLabel.frame = CGRectMake(x, y, w, h);
}

-(void)setFont:(UIFont *)font
{
    [super setFont:font];
    self.placeholderLabel.font = font;
    [self setNeedsLayout];
}

-(void)setText:(NSString *)text
{
    [super setText:text];
    [self setNeedsLayout];
}

@end
